import { Injectable, BadRequestException } from '@nestjs/common';
import { Express } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { join } from 'path';
import { existsSync, mkdirSync, unlinkSync } from 'fs';
@Injectable()
export class UploadService {
  private readonly uploadDir = join(process.cwd(), 'uploads');
  async saveFile(file: Express.Multer.File): Promise<string> {
    if (!file) {
      throw new BadRequestException('文件不能为空');
    }
    const uploadDir = path.join(__dirname, '..', '..', 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    const fileName = `${Date.now()}-${file.originalname}`;
    const filePath = path.join(uploadDir, fileName);
    fs.writeFileSync(filePath, file.buffer);

    return `${filePath}`;
  }
  constructor() {
    this.ensureUploadDirectoryExists();
  }

  private ensureUploadDirectoryExists() {
    if (!existsSync(this.uploadDir)) {
      mkdirSync(this.uploadDir, { recursive: true });
    }
  }
  async saveFile2(file: Express.Multer.File) {
    if (!file) {
      throw new BadRequestException('文件不能为空');
    }

    const fileInfo = {
      originalName: file.originalname,
      filename: file.filename,
      size: file.size,
      mimetype: file.mimetype,
      uploadTime: new Date(),
      url: `/files/${file.filename}`, // 直接访问的URL
      downloadUrl: `/files/download/${file.filename}`, // 下载URL
    };

    return fileInfo;
  }
  getFilePhysicalPath(filename: string): string {
    return join(this.uploadDir, filename);
  }
  async deleteFile(filename: string): Promise<boolean> {
    try {
      const filePath = this.getFilePhysicalPath(filename);
      if (existsSync(filePath)) {
        unlinkSync(filePath);
        return true;
      }
      return false;
    } catch (error) {
      throw new BadRequestException('文件删除失败');
    }
  }

  async fileExists(filename: string): Promise<boolean> {
    const filePath = this.getFilePhysicalPath(filename);
    return existsSync(filePath);
  }
}
